import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_info_entity.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'home_controller.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Get.put(HomeController());
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        backgroundColor: Colours.color_background,
        body: SafeArea(
          child: GetBuilder<HomeController>(
            builder: (controller) {
              return MultiStateWidget(
                child: SmartRefresher(
                  controller: controller.refreshController,
                  onRefresh: controller.onRefresh,
                  child: Stack(
                    alignment: Alignment.topCenter,
                    children: [
                      buildBackgroundWidget(),
                      Positioned(
                        child: Column(
                          children: [
                            buildAmountWidget(context, controller),
                            buildTransactionFlowWidget(controller),
                            buildFunctionMenuWidget(context, controller),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                state: controller.multiState,
                onRetry: () {
                  controller.onRetry();
                },
              );
            },
          ),
        ),
      ),
    );
  }

  Widget buildBackgroundWidget() {
    return Positioned(
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
      child: Image.asset(
        "images/bg_home.png",
        fit: BoxFit.fill,
      ),
    );
  }

  Widget buildAmountWidget(BuildContext context, HomeController controller) {
    if (controller.isAdmin) {
      return Card(
        margin: EdgeInsets.only(left: 16.w, top: 12.w, right: 16.w, bottom: 0.w),
        elevation: 5,
        color: Colours.color_white_30,
        shadowColor: Colours.color_0f112e_90,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  buildChangeCompanyWidget(controller),
                  Visibility(
                    visible: controller.isShowAmountWidget,
                    child: buildShowOrHideAmountWidget(controller),
                  ),
                ],
              ),
              Visibility(
                visible: controller.isShowAmountWidget,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 13.w),
                    Row(
                      children: [
                        Text(
                          controller.isAdmin ? "总余额(元)" : "",
                          style: TextStyle(
                            color: Colours.color_6f7082,
                            fontSize: 14.sp,
                          ),
                        ),
                        SizedBox(width: controller.isAdmin ? 9.w : 0),
                        buildTotalAmountWidget(controller),
                      ],
                    ),
                    SizedBox(height: controller.amountDetailList.isNotEmpty ? 20.w : 0),
                    buildAmountListWidget(context, controller),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return Visibility(
        visible: controller.isShowAmountWidget,
        child: Card(
          margin: EdgeInsets.only(left: 16.w, top: 12.w, right: 16.w, bottom: 0.w),
          elevation: 5,
          color: Colours.color_white_30,
          shadowColor: Colours.color_0f112e_90,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.w),
          ),
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "车队账户余额(元)",
                      style: TextStyle(
                        color: Colours.color_6f7082,
                        fontSize: 14.sp,
                      ),
                    ),
                    buildShowOrHideAmountWidget(controller),
                  ],
                ),
                SizedBox(height: 13.w),
                buildTotalAmountWidget(controller),
                SizedBox(height: controller.amountDetailList.isNotEmpty ? 20.w : 0),
                buildAmountListWidget(context, controller),
              ],
            ),
          ),
        ),
      );
    }
  }

  Widget buildChangeCompanyWidget(HomeController controller) {
    return Material(
      color: Colours.color_transparent,
      child: InkWell(
        onTap: () {
          controller.changeCompany();
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              controller.companyName,
              style: TextStyle(
                color: Colours.color_text_theme,
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(
              width: 8.w,
            ),
            Visibility(
              visible: controller.companyList.length > 1,
              child: Image.asset("images/ic_triangle.png"),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildShowOrHideAmountWidget(HomeController controller) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        controller.changeShowAmount();
      },
      child: Padding(
        padding: EdgeInsets.only(left: 5.w, top: 5.w, bottom: 5.w),
        child: Image.asset("images/ic_${controller.isShowAmount ? "show" : "hide"}_amount.png"),
      ),
    );
  }

  Widget buildTotalAmountWidget(HomeController controller) {
    return Text(
      FormatUtils.formatMoney(controller.totalAmount, showMoney: controller.isShowAmount),
      style: TextStyle(
        color: Colours.color_text_theme,
        fontSize: 24.sp,
        fontWeight: FontWeight.bold,
        height: controller.isShowAmount ? 1 : 1,
      ),
    );
  }

  Widget buildAmountListWidget(BuildContext context, HomeController controller) {
    return Visibility(
      visible: controller.amountDetailList.isNotEmpty,
      child: MediaQuery.removePadding(
        removeTop: true,
        removeBottom: true,
        context: context,
        child: GridView.builder(
          itemCount: controller.amountDetailList.length,
          shrinkWrap: true,
          physics: BouncingScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: controller.amountDetailList.isNotEmpty ? controller.amountDetailList.length : 3,
            mainAxisSpacing: 0,
            crossAxisSpacing: 10.w,
            mainAxisExtent: 45.w,
          ),
          itemBuilder: (context, index) {
            return buildAmountItemWidget(controller, index);
          },
        ),
      ),
    );
  }

  Widget buildAmountItemWidget(HomeController controller, int index) {
    CompanyInfoAmountDetail amountDetail = controller.amountDetailList[index];
    return Row(
      children: [
        Expanded(
          child: Material(
            color: Colours.color_transparent,
            child: InkWell(
              onTap: () {
                controller.onAmountClick(index);
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    amountDetail.name ?? "",
                    style: TextStyle(
                      color: Colours.color_6f7082,
                      fontSize: 12.sp,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(
                    height: 5.w,
                  ),
                  Text(
                    FormatUtils.formatMoney(amountDetail.amount, unit: "元", showMoney: controller.isShowAmount),
                    style: TextStyle(
                      color: Colours.color_text_theme,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(left: 10.w),
          color: index == controller.amountDetailList.length - 1 ? Colours.color_transparent : Colours.color_e5e6e6,
          width: 1.w,
          height: 12.w,
        )
      ],
    );
  }

  Widget buildTransactionFlowWidget(HomeController controller) {
    return Card(
      margin: EdgeInsets.only(
        left: 16.w,
        top: 12.w,
        right: 16.w,
      ),
      elevation: 5,
      color: Colours.color_white_30,
      shadowColor: Colours.color_0f112e_90,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.w),
        child: Material(
          color: Colours.color_transparent,
          child: InkWell(
            onTap: () {
              if (controller.companyId.isNotEmpty) {
                Get.toNamed(Routes.transactionFlow, arguments: {
                  Constant.PARAM_COMPANY_ID: controller.companyId,
                  Constant.PARAM_COMPANY_NAME: controller.companyName,
                  Constant.PARAM_COMPANY_LIST: controller.companyList,
                });
              }
            },
            child: Padding(
              padding: EdgeInsets.symmetric(
                vertical: 12.w,
                horizontal: 16.w,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "交易管理",
                          style: TextStyle(
                            color: Colours.color_text_theme,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(
                          height: 13.w,
                        ),
                        Row(
                          children: [
                            Text(
                              "本月消费",
                              style: TextStyle(
                                color: Colours.color_text_theme,
                                fontSize: 12.sp,
                              ),
                            ),
                            SizedBox(
                              width: 12.w,
                            ),
                            Text(
                              FormatUtils.formatMoney(controller.currentMonthAmount, unit: "元"),
                              style: TextStyle(
                                color: Colours.color_text_theme,
                                fontSize: 16.sp,
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 12.w),
                              width: 1.w,
                              height: 10.w,
                              color: Colours.color_e5e6e6,
                            ),
                            Text(
                              FormatUtils.formatMoney(controller.currentMonthOrderQuantity, unit: "升"),
                              style: TextStyle(
                                color: Colours.color_text_theme,
                                fontSize: 16.sp,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Image.asset("images/ic_arrow_right_gray.png"),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget buildFunctionMenuWidget(BuildContext context, HomeController controller) {
    return Expanded(
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 6.w, horizontal: 16.w),
        child: MediaQuery.removePadding(
          removeTop: true,
          removeBottom: true,
          context: context,
          child: GridView.builder(
            itemCount: controller.mainMenuList.length,
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 0,
              crossAxisSpacing: 5.w,
              mainAxisExtent: 90.w,
            ),
            itemBuilder: (context, index) {
              return buildFunctionMenuItemWidget(index, controller);
            },
          ),
        ),
      ),
    );
  }

  Widget buildFunctionMenuItemWidget(int index, HomeController controller) {
    MainMenu mainMenu = controller.mainMenuList[index];
    return Material(
      color: Colours.color_transparent,
      child: InkWell(
        onTap: () {
          controller.onMenuClick(mainMenu.name);
        },
        child: Padding(
          padding: EdgeInsets.all(10.w),
          child: Badge(
            position: BadgePosition.topEnd(top: -10.w, end: 0.w),
            padding: EdgeInsets.all(5.w),
            showBadge: mainMenu.name == "MessageRemind" && controller.unreadMessageCount > 0,
            badgeColor: Colours.color_ff3b30,
            badgeContent: Text(
              controller.unreadMessageCount.toString(),
              style: TextStyle(
                color: Colours.color_white,
                fontSize: 12.sp,
              ),
            ),
            animationType: BadgeAnimationType.scale,
            child: Column(
              children: [
                Container(
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: mainMenu.color,
                        offset: Offset(0.0, 5.w),
                        blurRadius: 10.w,
                      ),
                    ],
                  ),
                  child: Image.asset(
                    mainMenu.icon,
                    fit: BoxFit.cover,
                    height: 46.w,
                    width: 46.w,
                  ),
                ),
                SizedBox(
                  height: 5.w,
                ),
                Text(
                  mainMenu.title,
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
